<template>
  <div class="student-info-container">
    <h2 class="text-xl font-bold mb-4">学生基本信息</h2>

    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-form mb-6">
      <el-form-item label="学号" class="custom-select">
        <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
      </el-form-item>
      <el-form-item label="姓名" class="custom-select">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="班主任" class="custom-select1">
        <el-input v-model="searchForm.teacher" placeholder="请输入班主任" clearable />
      </el-form-item>

      <el-form-item label="班级">
        <el-select
          v-model="searchForm.class"
          placeholder="请选择班级"
          clearable
          class="custom-select"
        >
          <el-option
            v-for="item in classOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-card shadow="never" class="mb-6">
      <el-table :data="currentTableData" border style="width: 100%">
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="class" label="班级" width="120" />
        <el-table-column prop="phone" label="联系方式" width="120" />
        <el-table-column prop="teacher" label="班主任" width="100" />
        <el-table-column prop="teacherPhone" label="班主任联系方式" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container mt-4">
        <el-pagination
          background
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑学生信息" width="50%">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editForm.studentId" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-input v-model="editForm.class" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="班主任" prop="teacher">
          <el-input v-model="editForm.teacher" />
        </el-form-item>
        <el-form-item label="班主任联系方式" prop="teacherPhone">
          <el-input v-model="editForm.teacherPhone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([
  {
    studentId: '2023001',
    name: '白',
    class: '计算机1班',
    phone: '13800138001',
    teacher: '李老师',
    teacherPhone: '13800138002'
  },
  {
    studentId: '2023002',
    name: '李四',
    class: '计算机2班',
    phone: '13800138002',
    teacher: '王老师',
    teacherPhone: '13800138003'
  },
  {
    studentId: '2023003',
    name: '王五',
    class: '计算机3班',
    phone: '13800138003',
    teacher: '赵老师',
    teacherPhone: '13800138004'
  }
])

// 搜索表单
const searchForm = ref({
  studentId: '',
  name: '',
  class: '',
  teacher: ''
})

const classOptions = ref([
  { value: '计算机1班', label: '计算机1班' },
  { value: '计算机2班', label: '计算机2班' },
  { value: '计算机3班', label: '计算机3班' }
])

// 分页
const total = ref(tableData.value.length)
const pageSize = ref(5)
const currentPage = ref(1)

// 编辑对话框
const dialogVisible = ref(false)
const editForm = ref({
  studentId: '',
  name: '',
  class: '',
  phone: '',
  teacher: '',
  teacherPhone: ''
})

const editFormRef = ref(null)
let editingIndex = -1

// 编辑表单验证规则
const editRules = reactive({
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  teacherPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

// 计算属性：当前页显示的数据
const currentTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTableData.value.slice(start, end)
})

// 过滤后的表格数据
const filteredTableData = ref(tableData.value)

// 方法
const handleSearch = () => {
  const { studentId, name, class: classValue, teacher } = searchForm.value
  filteredTableData.value = tableData.value.filter(item => {
    return (
      (!studentId || item.studentId.includes(studentId)) &&
      (!name || item.name.includes(name)) &&
      (!classValue || item.class.includes(classValue)) &&
      (!teacher || item.teacher.includes(teacher))
    )
  })
  console.log('搜索条件:', searchForm.value)
  // 更新总数和重置当前页
  total.value = filteredTableData.value.length
  currentPage.value = 1
}

const resetSearch = () => {
  searchForm.value = {
    studentId: '',
    name: '',
    class: '',
    teacher: ''
  }
  filteredTableData.value = tableData.value
  // 重置总数和当前页
  total.value = tableData.value.length
  currentPage.value = 1
}

const handleEdit = (row) => {
  editingIndex = tableData.value.findIndex(item => item.studentId === row.studentId)
  editForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该学生信息吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value = tableData.value.filter(item => item.studentId !== row.studentId)
    handleSearch() // 重新应用搜索条件
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const confirmEdit = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      if (editingIndex >= 0) {
        tableData.value[editingIndex] = { ...editForm.value }
        handleSearch() // 重新应用搜索条件
      }
      ElMessage.success('修改成功')
      dialogVisible.value = false
    } else {
      ElMessage.error('表单验证失败，请检查输入')
      return false
    }
  })
}

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}
</script>

<style scoped>
.student-info-container {
  padding: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 调整间距 */
}

.pagination-container {
  display: flex;
  justify-content: center; /* 使分页组件在水平方向居中 */
  margin-top: 16px;
}

/* 自定义班级选择框宽度 */
::v-deep .custom-select {
  width: 140px;
}

::v-deep .custom-select1 {
  width: 160px;
}
</style>